import currency from 'currency.js'

export function func(Vue) {
  // 深拷贝
  Vue.prototype.$deepCopy = value => {
    if (value) {
      return JSON.parse(JSON.stringify(value))
    } else {
      return null
    }
  }

  // 函数防抖
  Vue.prototype.$debounce = (func, wait, _ = this) => {
    return () => {
      _.timer && clearTimeout(_.timer)
      _.timer = setTimeout(func, wait)
    }
  }

  // 文件下载
  Vue.prototype.$downFile = res => {
    let fileName = res.headers['content-disposition'].split('=')
    // 获取文件名fileName
    fileName = fileName[fileName.length - 1]
    fileName = fileName.replace(/"/g, '')
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(res.data, fileName)
    } else {
      const blob = res.data
      // FileReader主要用于将文件内容读入内存
      const reader = new FileReader()
      reader.readAsDataURL(blob)
      // onload当读取操作成功完成时调用
      return new Promise(resolve => {
        reader.onload = function(e) {
          const a = document.createElement('a')

          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          resolve()
        }
      })
    }
  }

  // 文件下载（base64）
  Vue.prototype.$downFileByBase64 = (res, fileName) => {
    try {
      const myBlob = dataURLtoBlob(res.data)
      const myUrl = URL.createObjectURL(myBlob)
      const a = document.createElement('a')
      a.setAttribute('href', myUrl)
      a.setAttribute('download', fileName + '.xlsx')
      a.setAttribute('target', '_blank')
      const clickEvent = document.createEvent('MouseEvents')
      clickEvent.initEvent('click', true, true)
      a.dispatchEvent(clickEvent)
    } catch (error) {
      console.log(error)
      throw error
    }
  }

  //  是否是数字
  Vue.prototype.$isNumber = value => {
    return typeof value === 'number' && !isNaN(value)
  }

  // 判断字符长度（英文算0.5，其他算1）
  Vue.prototype.$stringLength = value => {
    if (!value) return 0
    const reg = new RegExp(/^[a-zA-Z]/)
    let count = 0
    for (const item of value) {
      if (reg.test(item)) {
        count = count + 0.5
      } else {
        count++
      }
    }
    return count
  }

  // floorNum
  // 输入框中只允许输入小数点和数字，小数点后只能跟4位或者n位
  Vue.prototype.$floorNum = (e, n = 4) => {
    const r1 = `^\\d*(\\.?\\d{0,${n - 1}})`
    const reg = new RegExp(r1, 'g')
    return (e.target.value = e.target.value.match(reg)[0] || null)
  }

  //  cost delta
  Vue.prototype.$costDeltaVal = scope => {
    // gcmCost*qty(new) - sap标准价*qty(base)
    if (scope.row.gcmCost || scope.row.gcmCost === 0) {
      return (
        Number(scope.row.gcmCost) * Number(scope.row.newQty) -
        Number(scope.row.baseSapStandardPrice) * Number(scope.row.baseQty)
      )
    } else {
      return ''
    }
  }

  // table sort (区分大小写)
  Vue.prototype.$sortByLower = (a, b, type) => {
    if (type === 'asc') {
      return String(a)
        .trim()
        .toLowerCase() >
        String(b)
          .trim()
          .toLowerCase()
        ? -1
        : 1
    } else {
      return String(b)
        .trim()
        .toLowerCase() >
        String(a)
          .trim()
          .toLowerCase()
        ? 1
        : -1
    }
  }

  // 时间格式化
  Vue.prototype.$dateFomate = dateFomate

  // 上一个月
  Vue.prototype.$preMonth = preMonth

  // 是否有权限
  // 是否有按钮权限
  Vue.prototype.$hasPer = bindButton => {
    return true
    //  if (store.getters['post/getSessionPostId'] === SUPER_POST_ID) {
    //    return true
    //  } else {
    //    return router.currentRoute.meta.buttons.indexOf(bindButton) > -1
    //  }
  }

  Vue.prototype.$calc = (v1, v2, action, options) => {
    let result = ''
    const calcOption = { precision: 0, ...options }
    switch (action) {
      case 'add':
        result = currency(v1, calcOption).add(v2).value
        break
      case 'subtract':
        result = currency(v1, calcOption).subtract(v2).value
        break
      case 'multiply':
        result = currency(v1, calcOption).multiply(v2).value
        break
      // distribute
      default:
        result = currency(v1, calcOption).distribute(v2)[0].value
        break
    }

    return result
  }
  Vue.prototype.$fdStatus = ({ code: code = -1, prop: prop = 'label' } = {}) => {
    const list = [
      { code: 10, label: '新增' },
      { code: 20, label: 'PBM Leader已分配PBM' },
      { code: 30, label: 'PBM已接收' },
      { code: 40, label: 'PBM已驳回' },
      { code: 50, label: 'PBM已分配GCM' },
      { code: 60, label: '估价中' },
      { code: 70, label: '已审批' },
      { code: 80, label: '已报价' }
    ]

    if (code === -1) return list

    const item = list.find(item => String(item.code) === String(code))

    return item && item[prop]
  }
}

function dataURLtoBlob(dataurl) {
  const bstr = atob(dataurl)
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr])
}

export function dateFomate(date, format) {
  var paddNum = function(num) {
    num += ''
    return num.replace(/^(\d)$/, '0$1')
  }
  // 指定格式字符
  var cfg = {
    yyyy: date.getFullYear(), // 年:4位
    yy: date
      .getFullYear()
      .toString()
      .substring(2), // 年:2位
    M: date.getMonth() + 1, // 月:如果1位的时候不补0
    MM: paddNum(date.getMonth() + 1), // 月:如果1位的时候补0
    d: date.getDate(), // 日:如果1位的时候不补0
    dd: paddNum(date.getDate()), // 日:如果1位的时候补0
    hh: date.getHours(), // 时
    mm: date.getMinutes(), // 分
    ss: date.getSeconds() // 秒
  }
  format || (format = 'yyyy-MM-dd hh:mm:ss')
  return format.replace(/([a-z])(\1)*/gi, function(m) {
    return cfg[m]
  })
}

export function preMonth(date) {
  var arr = date.split('-')
  var year = arr[0] // 获取当前日期的年份
  var month = arr[1] // 获取当前日期的月份
  var day = arr[2] // 获取当前日期的日
  var year2 = year
  var month2 = parseInt(month) - 1
  if (month2 === 0) {
    year2 = parseInt(year2) - 1
    month2 = 12
  }
  var day2 = day
  var days2 = new Date(year2, month2, 0)
  days2 = days2.getDate()
  if (day2 > days2) {
    day2 = days2
  }
  if (month2 < 10) {
    month2 = '0' + month2
  }
  var t2 = year2 + '-' + month2 + '-' + day2
  return t2
}

// blob转成json
export function blobToJson(blobData) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader() // 创建读取文件对象
    reader.onloadend = () => {
      const res = JSON.parse(reader.result) // 返回的数据
      resolve(res)
    }
    reader.onerror = err => {
      reject(err)
    }
    reader.readAsText(blobData, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
  })
}
